# -*- coding: utf-8 -*-
# @Time        :2025/9/5 10:15
# @Author      :文刀水寿
# @File        : independent_records.py
"""
 @Description :
"""
import logging
from Browser.views import browser_process

logger = logging.getLogger(__name__)


def process_independent_records(records, target_table_id, feishu_bitable):
    """
    通用独立处理函数：处理单组独立记录（record3 或 record4）
    """
    updated_records = []

    for record in records:
        fields = record.get('fields', {})
        record_id = record.get('record_id')

        extracted = {
            '小红书昵称': fields.get('小红书昵称', [{}])[0].get('text', ''),
            '顺序': fields.get('顺序'),
            '收藏量': fields.get('收藏量', [{}])[0].get('text', ''),
            '点赞量': fields.get('点赞量', [{}])[0].get('text', ''),
            '评论量': fields.get('评论量', [{}])[0].get('text', ''),
            '分享': fields.get('分享', [{}])[0].get('text', ''),
            'ID号': fields.get('ID号', [{}])[0].get('text', ''),
            '粉丝量': fields.get('粉丝量', 0),
            '赞藏量': fields.get('赞藏量', 0),
            '团队账号': fields.get('团队账号', 0),
            '发布链接': fields.get('发布链接', {}).get('link', ''),
            '小红书主页链接': fields.get('小红书主页链接', {}).get('link', ''),
            'record_id': record_id
        }

        updated_stats = None
        if extracted['发布链接']:
            try:
                updated_stats = browser_process(
                    table_id3=target_table_id,
                    table_id4=None,
                    url=extracted['发布链接'],
                    need_fields=['收藏量', '点赞量', '评论量', '分享']
                )
            except Exception as e:
                logger.error(e)
                updated_stats = None

        if updated_stats and isinstance(updated_stats, dict):
            extracted['点赞量'] = updated_stats.get('点赞量', extracted['点赞量'])
            extracted['收藏量'] = updated_stats.get('收藏量', extracted['收藏量'])
            extracted['评论量'] = updated_stats.get('评论量', extracted['评论量'])
            extracted['分享'] = updated_stats.get('分享', extracted['分享'])

            update_fields = {
                '收藏量': extracted['收藏量'],
                '点赞量': extracted['点赞量'],
                '评论量': extracted['评论量'],
                '分享': extracted['分享']
            }
            feishu_result = feishu_bitable.update_record(
                fields=update_fields,
                table_id=target_table_id,
                record_id=record_id
            )

        updated_records.append(extracted)

    return updated_records
